module.exports = {
  /**
   * 海报购买记录
   * @url user/kh/postOrderConfig 前端调用的url参数地址
   */
  main: async (event) => {
    let {
      data = {}, userInfo, util, originalParam
    } = event;
    let {
      uniID,
      pubFun,
      vk,
      db,
      _
    } = util;
    let res = {
      code: 0,
      msg: "ok",
    };
    let couponName = "vk-coupon";
    let userName = "uni-id-users";
    let bonusSetName = "vk-bonus-set";
    let withdrawSetName = "vk-withdraw-set";
    let bonusRelateName = "vk-bonus-relate";
    let {
      sign_id,
      pid,
      coupon_id,
      stock,
      contract_no,
      time_stamp
    } = data;

    // 减库存 改状态
    let couponRes = await db
      .collection(couponName)
      .where({
        _id: coupon_id,
      })
      .get();
    let couponInfo;
    if (couponRes.data.length > 0) {
      couponInfo = couponRes.data[0];
      await vk.baseDao.update({
          dbName: couponName,
          whereJson: {
            _id: coupon_id,
          },
          dataJson: {
            stock: couponInfo.stock - stock,
            status: couponInfo.stock - stock > 0 ? 1 : 2,
          },
        },
        event.util
      );
    }
    // 消费金额   + 级别  + 流水
    let userRes = await db
      .collection(userName)
      .where({
        _id: sign_id,
      })
      .get();
      // 购买人信息
    let userBuyInfo
    if (userRes.data.length > 0) {
      userBuyInfo = userRes.data[0];
      // 获取级别设置
      let withdrawSetRes = await db
        .collection(withdrawSetName)
        .where({
          type: 3,
        })
        .get();
      // water_id water_name water_amount 7000  70000   700000  7000000
      let index = 0;
      for (let i = 0; i < withdrawSetRes.data.length; i++) {
        if (
          parseInt(userBuyInfo.water_amount) + stock * couponInfo.price >
          parseInt(withdrawSetRes.data[i].water_amount)
        ) {
          if (parseInt(userBuyInfo.water_amount) + stock * couponInfo.price <
            parseInt(withdrawSetRes.data[i + 1].water_amount) && withdrawSetRes.data[i + 1].water_amount)
            index = i;
          break;
        }
        if (
          parseInt(userBuyInfo.water_amount) + stock * couponInfo.price ==
          parseInt(withdrawSetRes.data[i].water_amount)
        ) {
          index = i;
          break;
        }
      }
      if (!userBuyInfo.water_amount) {
        userBuyInfo.water_amount = 0;
        userBuyInfo.water_amount_back = 0;
      }
      await db
        .collection(userName)
        .doc(sign_id)
        .update({
          water_amount: parseInt(userBuyInfo.water_amount) + stock * parseInt(couponInfo.all_price),
          water_amount_back: parseInt(userBuyInfo.water_amount_back) + stock * parseInt(couponInfo.all_price),
          water_name: withdrawSetRes.data[index].water_name,
        });
    }

    // 获取分佣设置
    let bonusSetRes = await db
      .collection(bonusSetName)
      .where({
        relate_coupon_id: coupon_id,
      })
      .get();
    // 直推人信息
    let zhiTuiInfo
    // 间推人信息
    let jianTuiInfo
    if (bonusSetRes.data.length > 0) {
      let bonusSetResInfo = bonusSetRes.data[0];
      // 通过uid找pid  同过pid找pid  只找两级
      if (pid) {
        // 直推人
        let secondRes = await db
          .collection(userName)
          .where({
            _id: pid,
          })
          .get();
        if (secondRes.data.length > 0) {
          zhiTuiInfo = secondRes.data[0];
          // 必须是购买过的
          if (zhiTuiInfo.water_name) {
            // 创建关系之前先检测旧的关系
            
            let tuijianRes = await db
              .collection(bonusRelateName)
              .where({
                origin_id: userBuyInfo._id,
                tuijian_id: zhiTuiInfo._id,
              })
              .get();
            let index = -1
            if (tuijianRes.data.length > 0) {
              for (let j = 0; j < tuijianRes.data.length; j++) {
                let now = vk.pubfn.timeFormat(vk.pubfn.getOffsetTime(time_stamp, {
                  day: 1,
                  mode: "after",
                }), "yyyy-MM-dd")
                if (now >= tuijianRes.data[j].tuijian_start_time && now <= tuijianRes.data[j].tuijian_expire_time) {
                  index = j
                  break
                }
              }
            }
            if (index > -1) {
              // 推荐人 关系内又买了包     更新合同  更新每日释放
              await vk.baseDao.update({
                  dbName: bonusRelateName,
                  whereJson: {
                    _id: tuijianRes.data[index]._id,
                  },
                  dataJson: {
                    status: 1,
                    contract_no: tuijianRes.data[index].contract_no + ',' + contract_no,
                    tuijian_per_bonus: tuijianRes.data[index].tuijian_per_bonus + (bonusSetResInfo.first * stock * couponInfo.per_bonus) / 100
                  },
                },
                event.util
              );
            } else {
              await vk.baseDao.add({
                dbName: bonusRelateName,
                dataJson: {
                  status: 1,
                  origin_id: userBuyInfo._id,
                  origin_name: userBuyInfo.username || userBuyInfo.nickname,
                  contract_no,
                  tuijian_id: zhiTuiInfo._id,
                  tuijian_name: zhiTuiInfo.username || zhiTuiInfo.nickname,
                  tuijian_per_bonus: (bonusSetResInfo.first * stock * couponInfo.per_bonus) / 100,
                  tuijian_start_time: vk.pubfn.timeFormat(vk.pubfn.getOffsetTime(time_stamp, {
                    day: 1,
                    mode: "after", // after 之后 before 之前
                  }), "yyyy-MM-dd"),
                  tuijian_expire_time: vk.pubfn.timeFormat(vk.pubfn.getOffsetTime(time_stamp, {
                    day: parseFloat(couponInfo.sign_day),
                    mode: "after", // after 之后 before 之前
                  }), "yyyy-MM-dd"),
                }
              }, event.util);
            }
          }
          if (zhiTuiInfo.pid) {
            // 间推人
            let thirdRes = await db
              .collection(userName)
              .where({
                _id: zhiTuiInfo.pid,
              })
              .get();
            if (thirdRes.data.length > 0) {
              jianTuiInfo = thirdRes.data[0];
              if (jianTuiInfo.water_name) {
                
                let tuijianRes = await db
                  .collection(bonusRelateName)
                  .where({
                    origin_id: userBuyInfo._id,
                    tuijian_id: jianTuiInfo._id,
                  })
                  .get();
                let index = -1
                if (tuijianRes.data.length > 0) {
                  for (let j = 0; j < tuijianRes.data.length; j++) {
                    let now = vk.pubfn.timeFormat(vk.pubfn.getOffsetTime(time_stamp, {
                      day: 1,
                      mode: "after", // after 之后 before 之前
                    }), "yyyy-MM-dd")
                    if (now >= tuijianRes.data[j].tuijian_start_time && now <= tuijianRes.data[j].tuijian_expire_time) {
                      index = j
                      break
                    }
                  }
                }
                if (index > -1) {
                  await vk.baseDao.update({
                      dbName: bonusRelateName,
                      whereJson: {
                        _id: tuijianRes.data[index]._id,
                      },
                      dataJson: {
                        status: 1,
                        contract_no: tuijianRes.data[index].contract_no + ',' + contract_no,
                        tuijian_per_bonus: tuijianRes.data[index].tuijian_per_bonus + (bonusSetResInfo.first * stock * couponInfo.per_bonus) / 100
                      },
                    },
                    event.util
                  );
                } else {
                  await vk.baseDao.add({
                    dbName: bonusRelateName,
                    dataJson: {
                      status: 1,
                      origin_id: userBuyInfo._id,
                      origin_name: userBuyInfo.username || userBuyInfo.nickname,
                      contract_no,
                      tuijian_id: jianTuiInfo._id,
                      tuijian_name: jianTuiInfo.username || jianTuiInfo.nickname,
                      tuijian_per_bonus: (bonusSetResInfo.second * stock * couponInfo.per_bonus) / 100,
                      tuijian_start_time: vk.pubfn.timeFormat(vk.pubfn.getOffsetTime(time_stamp, {
                        day: 1,
                        mode: "after", // after 之后 before 之前
                      }), "yyyy-MM-dd"),
                      tuijian_expire_time: vk.pubfn.timeFormat(vk.pubfn.getOffsetTime(time_stamp, {
                        day: parseFloat(couponInfo.sign_day),
                        mode: "after", // after 之后 before 之前
                      }), "yyyy-MM-dd"),
                    }
                  }, event.util);
                }
              }
            }
          }
        }
      }
    }
    return res;
  },
};